# coding: utf-8
# @Author : lryself
# @Date : 2022/1/26 9:40
# @Software: PyCharm
from sqlalchemy import create_engine, MetaData
from sqlalchemy.engine import reflection

from utils.config import get_database_url, readYML


def get_databases() -> list:
    url = get_database_url()
    engine = create_engine(url)
    metadata = MetaData(engine)
    metadata.reflect(engine, views=True)
    inspector = reflection.Inspector.from_engine(engine)

    tables = get_tables(
        metadata=metadata,
        inspector=inspector,
    )
    return tables


def get_tables(metadata, inspector: reflection.Inspector) -> list:
    """
        获取数据库数据
        :param inspector:
        :param metadata: sqlalchemy元数据
    """
    # Get all tables object
    table_objs = metadata.tables.values()
    table_list = []
    views = inspector.get_view_names()

    # Traverse each table object to get corresponding attributes to form an attribute dictionary
    for table in table_objs:
        table_name = str(table.name)
        table_dict = {}
        table_dict['table_name'] = table_name
        table_dict['columns'] = []
        # 是否是视图
        table_dict['is_view'] = True if table_name in views else False
        primaryKeys = inspector.get_pk_constraint(table_name)['constrained_columns']

        for column in inspector.get_columns(table_name):
            column_dict = {}
            # 字段名
            column_dict["field_name"] = str(column['name'])

            # 字段类型
            column_dict['field_type'] = str(column['type']).lower()
            # 是否可以为空
            column_dict['nullable'] = column['nullable']
            # 是否是自增键
            column_dict["autoincrement"] = column['autoincrement'] if column.get("autoincrement") else False
            # 是否是主键
            column_dict["primaryKey"] = True if str(column['name']) in primaryKeys else False
            # 字段说明
            column_dict["info"] = column["comment"]
            # 是否有默认值
            column_dict['exist_default'] = column["default"]

            table_dict['columns'].append(column_dict)
        table_list.append(table_dict)
    return table_list


if __name__ == '__main__':
    get_databases()
